Python Object oriented programming

Notes on python object oriented programming.


Class creation

Basic class creation with constructor, attributes and a simple method what is Class level attribute?


In [1]:
# Basic class
class Sample():
    pass

In [2]:
my_sample = Sample()

In [4]:
type(my_sample)


Out[4]:
__main__.Sample

In [5]:
# Parameters
class Dog():
    def __init__(self, breed):
        self.breed = breed

In [7]:
my_lab = Dog("lab")

In [8]:
my_lab.breed


Out[8]:
'lab'

In [18]:
# Shows a class with init and a class method
class Dog():
    def __init__(self, breed, name):
        self.breed = breed
        self.name = name
    def bark(self):
        print("{} is barking".format(self.name))

In [17]:
my_lab = Dog("Lab", "Jimmy")
my_lab.bark()


Jimmy is barking

In [19]:
# Class object attribute
class Circle():
    pi = 3.14 # This is common across all class objects
    def __init__(self, radius=1):
        self.radius = radius
    def calculateCircumference(self):
        return self.radius * self.pi * 2

In [26]:
my_c = Circle(10)
my_c.calculateCircumference()


Out[26]:
62.800000000000004

In [32]:
# Class object attribute
class Circle():
    pi = 3.14 # This is common across all class objects
    def __init__(self, radius=1):
        self.radius = radius
        #self.area = radius * radius * self.pi
        self.area = radius * radius * Circle.pi # Class level attributes can also be called this way!
    def calculateCircumference(self):
        return self.radius * self.pi * 2

In [33]:
c = Circle()

In [34]:
c.area


Out[34]:
3.14

In [35]:
c.radius


Out[35]:
1

In [36]:
c.calculateCircumference()


Out[36]:
6.28

Inheritance and Polymorphism


In [44]:
class Animal():
    def __init__(self):
        print("Animal created")
    def eat(self):
        print("Animal am eating")
    def sleep(self):
        print("Animal am sleeping")

In [45]:
a = Animal()


Animal created

In [46]:
a.eat()
a.sleep()


Animal am eating
Animal am sleeping

In [51]:
class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        print("Dog created")
    def bark(self):
        print("Dog is barking")

In [52]:
d = Dog()


Animal created
Dog created

In [53]:
d.eat()


Animal am eating

In [54]:
d.sleep()


Animal am sleeping

In [55]:
d.bark()


Dog is barking

In [ ]: